import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/page-layout/auth/auth.service';
import { UtilMethod } from 'src/environments/environment';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { LOGIN_PASSWORD_ERROR, LOGIN_SUCCESS, LOGIN_USER_ERROR } from 'src/app/bean/responseStatus';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

    /** 用户表单 */
    userForm: FormGroup;

  user = {
    name : '',
    password : ''
  };

  loading = false;

  jigsawFlag = false;

  constructor(private formBuilder: FormBuilder, /** 表单 */
              private router: Router, /** 路由 */
              private _notification: NzNotificationService, /** 提示 */
              public authService: AuthService,
              private http: HttpClient
    ) {
      this.userForm = this.formBuilder.group({
      username: [null, [this.confirmValidator]],
      password: [null, [this.confirmValidator]]
  });
  }
  /** 表单验证 */
  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (control.value === '') {
        return { briefConfirm: true };
      }
    return {};
  }

  async ngOnInit(): Promise<void> {
    // const data1 =  await this.getYear();
    // console.log(data1[0]);
  }

  // async login(): Promise<void>  {

  //   const data = await this.toLogin();
  //   console.log('data=' + data);
  //   if (data > 0) {
  //     AuthService.isLoggedIn = true;
  //     sessionStorage.setItem('uid', data);
  //     this.router.navigate([this.authService.redirectUrl]);
  //   }
  // }

  toLogin(userForm: any): any {
    const param = '/user/login?name=' + userForm.username + '&pw=' + userForm.password;

    console.log('/user/login->param=' + param);
    const data = this.http.get(UtilMethod.MONITOR_DEV_API + param).toPromise();
    return data;
  }

  async submit(userForm: any): Promise<void>  {
    if (userForm.username === ''){
      this._notification.create('error', '系统提醒', '请输入用户名!');
      return;
    }
    if (userForm.password === ''){
      this._notification.create('error', '系统提醒', '请输入密码!');
      return;
    }
    this.loading = true;
    const data = await this.toLogin(userForm);
    console.log(data.code);
    if (data.code === LOGIN_SUCCESS){
      this._notification.create(
        'success',
        '系统提醒',
        '登录成功'
      );
      /** 将用户信息存到session */
      window.sessionStorage.setItem('uid', data.uid);
      window.sessionStorage.setItem('uname', data.uname);
      this.logSuccess();
    } else {
      switch (data.code){
        case LOGIN_PASSWORD_ERROR:
          this._notification.create(
            'error',
            '系统提醒:登录失败',
            '密码输入有误'
          );
          this.logError();
          break;
        case LOGIN_USER_ERROR:
          this._notification.create(
            'error',
            '系统提醒:登录失败',
            '没有该用户'
          );
          this.logError()
          break;
      }
    }
  }

  public setLoading(): void {
    this.loading = true;
    setTimeout(() => {
      this.loading = false;
    }, 1500);
  }

  /** 登陆失败方法 */
  public logError(): void {
    this.router.navigate(['/login']);
  }
  /** 登陆成功方法 */
  public logSuccess(): void {
    this.router.navigate(['pages/console']);
  }

  public register(): void {
    this.router.navigate(['/login/register']);
  }

}
